package com.yc.db.jdbc;

import java.sql.*;

/**
 * Created with IntelliJ IDEA.
 * description:
 * author: yc
 * date: 2021/4/1 16:18
 */
public class C1 {
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost/world?useSSL=false";

    static final String USER = "root";
    static final String PASS = "123456";

    public void jdbc1() {
        Connection conn = null;
        Statement stmt = null;

        try {
//            Class.forName(JDBC_DRIVER);//Register JDBC driver
            System.out.println("Connection to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // Execute a query
            System.out.println("Create statement...");
            stmt = conn.createStatement();

            String sql = "SELECT * FROM city";
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                int id = rs.getInt("ID");
                String name = rs.getString("Name");
                String countryCode = rs.getString("CountryCode");
                String district = rs.getString("District");
                String population = rs.getString("Population");

                System.out.println("id:"+id+", name:"+name+", countryCode:"+countryCode+", district:"+district+", population:"+population);
            }

            //close env
            rs.close();

        }  catch (SQLException e) {
            e.printStackTrace();
        } finally {

            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        C1 c = new C1();
        c.jdbc1();
    }
}
